<template>
  <div id="app">
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <template #header>
            <div class="card-header">
              <span>订单列表</span>
              <el-button type="primary" @click="handleAddOrder">添加订单</el-button>
            </div>
          </template>
          <el-table :data="orders" border style="width: 100%">
            <el-table-column prop="orderId" label="订单编号">
            </el-table-column>
            <el-table-column prop="idCard" label="支付者证件号">
            </el-table-column>
            <el-table-column prop="idCardType" label="证件类型">
            </el-table-column>
            <el-table-column label="机票编号">
              <template #default="scope">
                <div v-for="ticket in scope.row.tickets" :key="ticket.id">
                  {{ ticket.id }}
                </div>
              </template>
            </el-table-column>
            <el-table-column label="乘机人证件号">
              <template #default="scope">
                <div v-for="ticket in scope.row.tickets" :key="ticket.id">
                  {{ ticket.idCard }}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalPrice" label="订单总价">
            </el-table-column>
            <el-table-column prop="status" label="订单状态">
            </el-table-column>
            <el-table-column prop="createTime" label="创建时间">
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleEditOrder(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="editDialogVisible" title="编辑订单" width="50%">
      <el-form :model="form" label-width="150px">
        <el-form-item label="支付者证件号">
          <el-input v-model="form.idCard" placeholder="请输入支付者证件号"></el-input>
        </el-form-item>
        <el-radio-group  v-model="form.status">
          <el-radio label="待支付">待支付</el-radio>
          <el-radio label="已支付">已支付</el-radio>
          <el-radio label="已取消">已取消</el-radio>
        </el-radio-group>
        <div style="margin-top:20px" v-for="(ticket, index) in form.tickets" :key="index">
          <el-form-item label="乘客证件号">
            <el-input v-model="ticket.idCard" placeholder="请输入乘客证件号"></el-input>
          </el-form-item>
          <el-form-item label="选择班次">
            <el-select
                v-model="selectFlights[index]"
                filterable
                placeholder="班次"
                @change="getTicketsBySelect(index)"
            >
              <el-option
                  v-for="item in flights"
                  :key="item.flightId"
                  :label="item.flightId"
                  :value="item.flightId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="座位">
            <el-button type="primary" @click="handleSelectSeat(index)">选择座位</el-button>
            <el-input disabled v-model="ticket.seatNumber"></el-input>
          </el-form-item>
          <el-button type="danger" @click="removeTicket(index, form.tickets)">删除</el-button>
        </div>
        <el-form-item label="总价格">
          <el-input v-model="form.totalPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTicket(form.tickets)">添加机票</el-button>
          <el-button type="primary" @click="handleSaveOrder">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="addDialogVisible" title="添加订单" width="50%">
      <el-form :model="form" label-width="150px">
        <el-form-item label="支付者证件号">
          <el-input v-model="form.idCard" placeholder="请输入支付者证件号"></el-input>
        </el-form-item>
        <el-radio-group  v-model="form.status">
          <el-radio label="待支付">待支付</el-radio>
          <el-radio label="已支付">已支付</el-radio>
          <el-radio label="已取消">已取消</el-radio>
        </el-radio-group>
        <div style="margin-top:20px" v-for="(ticket, index) in form.tickets" :key="index">
          <el-form-item label="乘客证件号">
            <el-input v-model="ticket.idCard" placeholder="请输入乘客证件号"></el-input>
          </el-form-item>
          <el-form-item label="选择班次">
            <el-select
                v-model="selectFlights[index]"
                filterable
                placeholder="班次"
                @change="getTicketsBySelect(index)"
            >
              <el-option
                  v-for="item in flights"
                  :key="item.flightId"
                  :label="item.flightId"
                  :value="item.flightId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="座位">
            <el-button type="primary" @click="handleSelectSeat(index)">选择座位</el-button>
            <el-input disabled v-model="ticket.seatNumber"></el-input>
          </el-form-item>
          <el-button type="danger" @click="removeTicket(index, form.tickets)">删除</el-button>
        </div>
        <el-form-item label="总价格">
          <el-input v-model="form.totalPrice" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addTicket(form.tickets)">添加机票</el-button>
          <el-button type="primary" @click="handleSaveOrder">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog v-model="seatDialogVisible" title="选择座位" width="50%">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-table :data="selectTickets[currentTicketIndex].tickets" border style="width: 100%">
            <el-table-column label="座位号" prop="seatNumber">
            </el-table-column>
            <el-table-column label="状态" prop="status">
            </el-table-column>
            <el-table-column label="价格" prop="price">
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="scope">
                <el-button type="primary" size="small" @click="handleSelectSeat(scope.row)" v-if="scope.row.status === '待售'">选择</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="seatDialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessage} from "element-plus";

export default {
  name: 'AdminCity',
  data() {
    return {
      flights: [],
      orders: [],
      addDialogVisible: false,
      editDialogVisible: false,
      selectFlights: [],
      selectTickets: [[]],
      seatDialogVisible: false,
      currentTicketIndex: null,
      form: {
        idCard: '',
        totalPrice: 0,
        status: '已支付',
        tickets: [],
      },
    };
  },
  mounted() {
    this.fetchFlights();
    this.fetchOrders();
  },
  methods: {
    fetchOrders(){
      axios.get('/order')
          .then(response => {
            this.orders = response.data;
          })
          .catch(error => {
            console.error('获取订单列表失败', error);
            ElMessage.error('获取订单列表失败');
          });
    },
    fetchFlights(){
      axios.get('/flight')
          .then(response => {
            this.flights = response.data;
          })
          .catch(error => {
            console.error('获取航班列表失败', error);
            ElMessage.error('获取航班列表失败');
          });
    },
    addTicket(tickets) {
      tickets.push({id:'',price:0, seatNumber: '',idCard: ''});
    },
    removeTicket(index, tickets) {
      this.clearTicket(index);
      tickets.splice(index, 1);
    },
    getTicketsBySelect(index){
      this.clearTicket(index);
      axios.get(`/flight/${this.selectFlights[index]}`)
          .then(response => {
            this.selectTickets[index] = response.data;
          })
          .catch(error => {
            console.error('获取选择的航班失败', error);
            ElMessage.error('获取选择的航班失败');
          });
      console.log(this.selectTickets);
    },
    clearTicket(index) {
      console.log(this.form.tickets[index]);
      if(this.form.tickets[index].id === ''){
        return;
      }
      else{
        const ticketDTO = {
          id: this.form.tickets[index].id,
          seatNumber: this.form.tickets[index].seatNumber,
          status: '0',
        }
        axios.post('/tickets', ticketDTO)
            .then(() => {
              this.form.tickets[index].id = '';
              this.form.tickets[index].seatNumber = '';
              this.form.tickets[index].price = 0;
              this.form.tickets[index].status = '待售';
            })
            .catch(error => {
              console.error('更新机票失败', error);
              ElMessage.error('更新机票失败');
            });
      }
    },
    handleEditOrder(order){
      this.form.idCard = order.idCard;
      this.form.totalPrice = order.totalPrice;
      this.form.status = order.status;
      this.form.tickets = order.tickets;
      for (let i = 0; i < this.form.tickets.length; i++) {
        this.selectFlights.push(this.form.tickets[i].flightId);
      }
      this.editDialogVisible = true;
    },
    handleSelectSeat(index) {
      if (typeof index === 'number') {
        this.clearTicket(index);
        this.currentTicketIndex = index;
        this.seatDialogVisible = true;
        this.getTicketsBySelect(this.currentTicketIndex);
      } else {
        this.form.tickets[this.currentTicketIndex].id = index.id;
        this.form.tickets[this.currentTicketIndex].seatNumber = index.seatNumber;
        this.form.tickets[this.currentTicketIndex].price = index.price;
        this.form.tickets[this.currentTicketIndex].status = '已被选择';
        const ticketDTO = {
          id: index.id,
          seatNumber: index.seatNumber,
          price: index.price,
          status: '3',
        }
        axios.post('/tickets/status',ticketDTO)
          .then(response => {
            console.log(response.data);
            if(response.data === true){
              this.form.totalPrice = 0;
              for (let i = 0; i < this.form.tickets.length; i++) {
                this.form.totalPrice += this.form.tickets[i].price;
              }
              this.seatDialogVisible = false;
            }
            else{
              ElMessage.error('该座位已被选择');
              this.getTicketsBySelect(this.currentTicketIndex);
            }
          }).catch(error => {
            console.error('更新座位状态失败', error);
            ElMessage.error('更新座位状态失败');
          });
      }
    },
    handleAddOrder() {
      this.addDialogVisible = true;
    },
    handleSaveOrder() {
      if(this.form.idCard === '' || this.form.tickets.length === 0){
        ElMessage.error('请填写完整信息');
        return;
      }
      for (let i = 0; i < this.form.tickets.length; i++) {
        if (this.form.tickets[i].id === '') {
          ElMessage.error('请选择机票');
          return;
        }
        if(this.form.tickets[i].idCard === ''){
          ElMessage.error('请填写乘客身份证号');
          return;
        }
      }
      if(this.form.status === '已支付'){
        for (let i = 0; i < this.form.tickets.length; i++) {
          this.form.tickets[i].status = '1';
        }
      }else if(this.form.status === '待支付'){
        for (let i = 0; i < this.form.tickets.length; i++) {
          this.form.tickets[i].status = '3';
        }
      }else if(this.form.status === '已取消'){
        for (let i = 0; i < this.form.tickets.length; i++) {
          this.form.tickets[i].status = '0';
        }
      }
      axios.post('/order', this.form)
          .then(() => {
            this.addDialogVisible = false;
            ElMessage.success('添加订单成功');
            location.reload();
          })
          .catch(() => {
            ElMessage.error('添加订单失败');
          });
    },
  },
};
</script>


<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

.box-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
